<template>
    <el-card shadow="always">
        <el-alert
            title="添加商品信息"
            type="info"
            center
            show-icon
            :closable="false"
        ></el-alert>
        <el-steps
            class="margin-bottom-20 margin-top-20"
            :active="step"
            align-center
        >
            <el-step v-for="s in steps" :key="s" :title="s"></el-step>
        </el-steps>
        <el-tabs tab-position="left" :before-leave="changeTabCheck">
            <el-tab-pane label="基本信息">
                <el-form label-position="top" style="padding-left: 20px" :rules="goodRules" :model="newGoods"
                    ref="goodFormOne"
                >
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="newGoods.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input type="number" v-model.number="newGoods.goods_price"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input type="number"  v-model.number="newGoods.goods_weight"></el-input>
                    </el-form-item>
                    <el-form-item label="商品库存" prop="goods_number">
                        <el-input type="number"  v-model.number="newGoods.goods_number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader
                            v-model="newGoods.goods_cat"
                            :options="options"
                            :props="{ label: 'cat_name', value: 'cat_id' }"
                            @change="loadAttrData"
                            style="width:100%"
                        ></el-cascader>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="商品参数">
				<el-form label-position="top" style="padding-left: 20px">
                    <el-form-item v-for="item in many" :label="item.attr_name" :key="item.attr_id">
                        <el-checkbox-group v-model="newGoods.attrs[item.attr_id]">
                            <el-checkbox border
                                v-for="(tip,i) in item.attr_vals" :key="i" 
                                :label="tip"
                            ></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
			</el-tab-pane>
            <el-tab-pane label="商品属性">
                <el-form label-position="top" style="padding-left: 20px">
                    <el-form-item v-for="item in only" :key="item.attr_id" :label="item.attr_name">
						<el-autocomplete style="width:100%"
							v-model="newGoods.attrs[item.attr_id]"
							:fetch-suggestions="(qs,cb)=>{ cb(item.attr_vals) }"
							placeholder="请输入内容"
						></el-autocomplete>
					</el-form-item>
				</el-form>
            </el-tab-pane>
            <el-tab-pane label="商品图片">
				<el-form label-position="top" style="padding-left: 20px">
                    <el-form-item label="商品图片">
                        <!-- 
                            element-ui 本身对组件 el-upload 进行主动上传方法的封装
                            问题：
                                1、页面需要构建请求地址
                                2、如果请求受限，需要定义请求头
                                3、响应结果的处理 - 通过判断上传的响应自定义状态，操作照片墙的显示
                        -->
                        <el-upload
                            :action="apiPath+'/upload'"
                            list-type="picture-card"
                            :headers="{ Authorization:token }"
                            :on-success="uploadFileSuccess"
                        >
                            <i class="el-icon-plus"></i>
                        </el-upload>
						<!-- <el-upload
							class="upload-demo"
							action="https://jsonplaceholder.typicode.com/posts/"
							:file-list="fileList"
							list-type="picture"
						>
							<el-button size="small" type="primary">点击上传</el-button>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
						</el-upload> -->
					</el-form-item>
				</el-form>
			</el-tab-pane>
            <el-tab-pane label="商品内容">
				<el-form label-position="top" style="padding-left: 20px">
					<el-form-item label="商品内容">
						<quill-editor v-model="newGoods.goods_introduce"></quill-editor>
					</el-form-item>
                    <el-button type="success" @click="addNewProduct">提交产品并添加</el-button>
				</el-form>
			</el-tab-pane>
            <el-tab-pane label="添加完成">
				<el-form label-position="top" style="padding-left: 20px">
					<el-form-item label="添加完成">
                        <!-- 清空相关数据-回到第一步 -->
						<el-button type="success">继续添加新产品</el-button>
						<el-button type="success">返回产品列表页</el-button>

					</el-form-item>
				</el-form>
			</el-tab-pane>
        </el-tabs>
    </el-card>
</template>
<script>
import { goodsRules } from '@/rules/goodRules.js'
import { loadCategories,loadCategoriesAttrs } from '@/api/categories.js'
export default {
    data() {
        return {
            apiPath:process.env.VUE_APP_API_BASE_URL,
            token:"",
            goodRules:goodsRules,
            newGoods:{
                goods_name:"测试",
                goods_cat:[],
                goods_price:100,
                goods_number:100,
                goods_weight:100,
                goods_introduce:"",
                pics:[],
                attrs:{}
            },
            many:[],
            only:[],
			fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
            test:"",
            step:0,
            steps: [
                "基本信息",
                "商品参数",
                "商品属性",
                "商品图片",
                "商品内容",
                "完成",
            ],
            options: [],
            checkRef:[
                "goodFormOne",
                null,
                null,
                null,
                null
            ]
        };
    },
    methods:{
        uploadFileSuccess({ data:{tmp_path  } }){
            console.log(tmp_path)
            this.newGoods.pics.push({
                pic:tmp_path
            })
        },
        changeTabCheck(index,oldIndex){
            if(oldIndex===undefined||oldIndex>index){
                this.step = index*1;
                return true;
            }
            // console.log( index-1,oldIndex );
            // console.log( (index-1)!=oldIndex*1 )
            if((index-1)!=oldIndex*1){
                // 因为该区域返回值会因为方法外围定义 async 导致阻止效果失效
                // 所以该返回结果中需要将外围的 async 移除，因此该方法内部不能使用 await
                this.$message.info("请按照步骤进行填写");
                return false;
            }
            // console.log(1);
            let key = this.checkRef[oldIndex];
            // 如果取值为null表示该tab不需要校验
            if(key===null){
                this.step = index*1;
                return true;
            }

            // 外围方法未定义 async 关键字，导致不能直接定义 await 将回调转换为同步操作
            // js 可以通过 自执行函数完成 方法的 主动触发
            // 因此自执行函数传递回调可以直接作为 async 修饰方法使用
            let flag = (async ()=>{
                return await this.$refs[key].validate();
            } )();
            if(flag) this.step = index*1;
            return flag;
        },
        async loadAttrData(ids){
            let many = await loadCategoriesAttrs(ids[2],{ sel:"many" });
            // console.log(many);
            many.forEach(item => {
                item.attr_vals = item.attr_vals.split(" ");
                // this.newGoods.attrs[item.attr_id] = [];
                this.$set(this.newGoods.attrs,item.attr_id,[]);
            });
            let only = await loadCategoriesAttrs(ids[2],{ sel:"only" });
            only.forEach(item => {
                item.attr_vals = item.attr_vals.split(" ");
                let arr = [];
                for (let str of item.attr_vals) {
                    arr.push({ value:str })
                }
                item.attr_vals = arr;
                this.$set(this.newGoods.attrs,item.attr_id,"");
            });
            this.many = many;
            this.only = only;
        },
        async initAllCategories(){
            let result = await loadCategories();
            if(!result) return;
            this.options = result;
        },
        addNewProduct(){
            // console.log(this.newGoods);
            let data = JSON.parse(JSON.stringify(this.newGoods));
            // console.log(data);
            data.goods_cat = data.goods_cat.toString();
            let temp = []
            for (let key in data.attrs) {
                temp.push({
                   attr_id: key, 
                   attr_value: Array.isArray(data.attrs[key])?data.attrs[key].join(" "):data.attrs[key]
                });
            }
            data.attrs = temp;
            console.log(data);
        }
    },
    created(){
        this.initAllCategories();
        let user = sessionStorage.getItem("user");
        if(user!=null){
            let { token } = JSON.parse(user);
            this.token =  token;
        }
        // console.log(process.env);
    }
};
</script>
<style lang="less" scoped>
.el-tabs {
    display: table-row;
    width: 100%;
}
.el-tabs::v-deep .el-tabs__header {
    float: none;
    height: 0px;
    display: table-cell;
}
.el-tabs::v-deep .el-tabs__content {
    display: table-cell;
    width: 100%;
}
.el-checkbox {
	margin-right: 10px;
	margin-bottom: 10px;
}
.el-checkbox.is-bordered+.el-checkbox.is-bordered {
    margin-left: 0px;
}
.quill-editor{
	line-height: normal!important;
}
.quill-editor::v-deep .ql-editor{
    min-height: 350px;
    // height: 800px;
    max-height: 600px;

}
</style>